<template>
    <div class="madp-article-list-edit">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <div v-if="radio === 0">
                <el-form-item label="文章内容:" prop="content">
                    <quill-editor
                        v-model="ruleForm.arBody"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @focus="onEditorFocus($event)"
                        @change="onEditorChange($event)"
                        v-loading="quillLoading"
                    ></quill-editor>
                </el-form-item>
                <el-form-item label="标题:" prop="title" class="madp-from">
                    <el-input v-model.trim="ruleForm.title" placeholder="请输入标题，确认后不能修改" :disabled="ruleForm.changeTitle == 1" maxlength="50" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="作者:" prop="arAuthor">
                    <el-input v-model.trim="ruleForm.arAuthor" placeholder="请输入作者" :disabled="ruleForm.changeTitle == 1" maxlength="20" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="文章描述:" prop="marketingDescribe">
                    <el-input
                        class="madp-marketing-describe"
                        type="textarea"
                        rows="4"
                        v-model.trim="ruleForm.marketingDescribe"
                        placeholder="请输入文章描述"
                        maxlength="100"
                        show-word-limit
                    ></el-input>
                </el-form-item>
                <el-form-item label="文章封面:" prop="marketingCover">
                    <el-upload
                        v-loading="loading"
                        :headers="headers"
                        class="avatar-uploader"
                        accept=".jpg, .jpeg, .png, .gif"
                        :auto-upload="false"
                        action="#"
                        :show-file-list="false"
                        :on-change="uploadChangeFile"
                        :file-list="fileList"
                    >
                        <img v-if="ruleForm.marketingCover" :src="ruleForm.marketingCover" class="madp-article-cover" />
                        <div v-else>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                    <p>只能上传不超过5M的文件</p>
                </el-form-item>
            </div>
            <el-form-item>
                <h4>文章追踪设置</h4>
                <el-checkbox class="madp-article-track-behavior" v-model="ruleForm.trackBehavior">行为通知(当客户点击文章时，发送文章的员工会收到消息提醒)</el-checkbox>
                <!-- <p class="madp-checked-dynamic">动态通知(当客户点击文章时，会将客户的打开行为记录在客户动态里)</p> -->
            </el-form-item>
            <el-form-item class="madp-buttons">
                <el-button type="primary" size="medium" @click="saveArticleForm('ruleForm', 1)" v-if="radio === 0">保存</el-button>
                <el-button type="primary" size="medium" @click="saveofficialForm('ruleForm', 1)" v-if="radio === 1">保存</el-button>
                <el-button type="primary" size="medium" @click="saveArticleForm('ruleForm', 3)" v-if="radio === 0">预览</el-button>
                <el-button type="primary" size="medium" @click="saveArticleForm('ruleForm', 2)" v-if="radio === 0">保存即发布</el-button>
                <el-button type="primary" size="medium" @click="saveofficialForm('ruleForm', 2)" v-if="radio === 1">保存即发布</el-button>
            </el-form-item>
        </el-form>
        <el-upload
            ref="uploadRef"
            :headers="headers"
            :show-file-list="false"
            :on-change="uploadChangeFile2"
            id="uploadRef"
            accept=".jpg, .jpeg, .png, .gif"
            :auto-upload="false"
            action="#"
        ></el-upload>
    </div>
</template>

<script>
import { quillEditor, Quill } from 'vue-quill-editor';
import ImageResize from '@felrov/quill-image-resize-module';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { newAndEditArticle, sysFileUpload, articleRelease, savePublishMaterial } from '@/api/customer-into/marketing-material';
import store from '@/store';
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
    ['blockquote', 'code-block'], // 引用  代码块
    [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
    [{ script: 'sub' }, { script: 'super' }], // 上标/下标
    [{ indent: '-1' }, { indent: '+1' }], // 缩进
    [{ direction: 'rtl' }], // 文本方向
    [{ size: ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px', false] }], // 字体大小，false设置自定义大小
    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
    [{ align: [] }], // 对齐方式
    ['link', 'image'],
    ['clean'] // 清除文本格式
];
// 自定义字体大小
let Size = Quill.import('attributors/style/size');
Size.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px', false];
Quill.register(Size, true);
Quill.register('modules/imageResize', ImageResize);
export default {
    components: {
        quillEditor
    },
    props: {
        sendArticleList: {
            type: Object,
            required: true
        },
        radio: {
            type: Number,
            default: 0
        },
        activeObj: {
            type: Object,
            default: () => {
                return {
                    activeIndex: 0
                };
            }
        }
    },
    watch: {
        'ruleForm.arBody': {
            handler(newVal, oldVal) {
                if (oldVal) {
                    this.$refs.ruleForm.validateField('content');
                }
            }
        },
        'ruleForm.marketingCover': {
            handler(val) {
                this.$refs.ruleForm.validateField('marketingCover');
            }
        }
    },
    data() {
        const validateContent = (rule, value, callback) => {
            if (!this.ruleForm.arBody) {
                callback(new Error('请输入文章内容'));
            } else if (!this.ruleForm.arBody.replaceAll(' ', '')) {
                callback(new Error('文章内容不能为纯空格'));
            } else {
                callback();
            }
        };
        const validateImg = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请上传封面图片'));
            } else {
                callback();
            }
        };
        return {
            // 富文本loading开关
            quillLoading: false,
            // 请求头
            headers: {
                Authorization: 'Bearer ' + store.getters.access_token,
                LdapToken: store.getters.ldap_token
            },
            // 富文本内容
            content: '',
            // 富文本配置项
            editorOption: {
                placeholder: '请填写文章内容',
                modules: {
                    //工具栏定义的
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            image: (value) => {
                                if (value) {
                                    // 在编辑器中点击图片 icon 会触发此事件
                                    this.$refs.uploadRef.$children[0].$refs.input.click();
                                }
                            }
                        }
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplaySize', 'Toolbar']
                    }
                }
            },
            // 表单对象
            ruleForm: {
                arBody: '',
                marketingCover: ''
            },
            // 表单校验规则
            rules: {
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                arAuthor: [{ required: true, message: '请输入作者', trigger: 'blur' }],
                marketingDescribe: [
                    {
                        required: true,
                        message: '请输入文章描述',
                        trigger: 'blur'
                    }
                ],
                marketingCover: [
                    {
                        required: true,
                        validator: validateImg,
                        trigger: 'change'
                    }
                ],
                content: [
                    {
                        required: true,
                        validator: validateContent,
                        trigger: 'change'
                    }
                ]
            },
            // 弹窗图片路径
            dialogImageUrl: '',
            // 弹簧开关
            dialogVisible: false,
            // loading开关
            loading: false,
            // 文件列表
            fileList: []
        };
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        }
    },
    created() {
        this.ruleForm = this.sendArticleList;
        this.ruleForm.trackBehavior = this.sendArticleList.trackBehavior == 0 ? false : true; //文章追踪-行为通知，0为未选中，1为选中，默认未选中
        this.ruleForm.trackDynamic = 1; //文章追踪-动态通知，0为未选中，1为选中，默认未选中
    },
    methods: {
        onEditorReady(editor) {
            // 准备编辑器
        },
        onEditorBlur() {}, // 失去焦点事件
        onEditorFocus() {}, // 获得焦点事件
        onEditorChange() {}, // 内容改变事件
        // 上传事件
        uploadChangeFile(file) {
            if (file && file.raw) {
                let fileMsg = file.raw;
                if (fileMsg.size / 1024 / 1024 > 5) {
                    this.fileList = [];
                    this.$message.error('上传不能超过5M');
                    return;
                }
                this.sysFileUploadFn(file);
            }
        },
        // 文件上传
        sysFileUploadFn(file) {
            let fd = new FormData();
            fd.append('file', file.raw);
            this.loading = true;
            sysFileUpload(fd)
                .then((res) => {
                    if (res.data.code === 0) {
                        let fileMsg = res.data.data;
                        this.ruleForm.marketingCover = fileMsg.url;
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        // 文件上传
        uploadChangeFile2(file) {
            if (file && file.raw) {
                let fileMsg = file.raw;
                if (fileMsg.size / 1024 / 1024 > 5) {
                    this.$message.error('上传不能超过5M');
                    return;
                }
                let fd = new FormData();
                fd.append('file', file.raw);
                this.quillLoading = true;
                sysFileUpload(fd)
                    .then((res) => {
                        if (res.data.code === 0) {
                            let url = res.data.data.url;
                            let quill = this.editor;
                            // 如果上传成功, 获取光标所在位置, 插入图片，res 为服务器返回的图片链接地址
                            if (res) {
                                let length = quill.getSelection().index;
                                quill.insertEmbed(length, 'image', url);
                                // 调整光标到最后
                                quill.setSelection(length + 1);
                            }
                        }
                        this.quillLoading = false;
                    })
                    .catch(() => {
                        this.quillLoading = false;
                    });
            }
        },
        //保存表单
        saveArticleForm(ruleForm, marketingState) {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (marketingState == 1 || marketingState == 2) {
                        this.$refs[ruleForm].validate((valid) => {
                            if (valid) {
                                this.newArticleFn(this.ruleForm, marketingState);
                            }
                        });
                    } else if (marketingState == 3) {
                        this.$emit('weChatShowFn', Object.assign(this.ruleForm));
                    }
                }
            });
        },
        //公众号素材保存
        saveofficialForm(ruleForm, marketingState) {
            if (marketingState == 1 || marketingState == 2) {
                let data = {
                    id: this.sendArticleList.id,
                    trackBehavior: this.ruleForm.trackBehavior ? 1 : 0,
                    trackDynamic: this.ruleForm.trackDynamic ? 1 : 0
                };
                savePublishMaterial(data).then((res) => {
                    if (res.data.code === 0) {
                        this.$message.success('保存并发布成功！');
                        this.MaterialList();
                        this.officialVisible = false;
                    }
                });
            }
        },
        // 新增文章
        newArticleFn(ruleForm, marketingState) {
            let obj = {
                classification: this.activeObj.id, //分类id
                arAttribute: ruleForm.radio, //文章属性，0为自有文章，1为公众号导入
                arAuthor: ruleForm.arAuthor, //文章作者
                arBody: ruleForm.arBody, //文章内容
                marketingCover: ruleForm.marketingCover, //文章封面
                marketingDescribe: ruleForm.marketingDescribe, //文章描述
                title: ruleForm.title, //文章标题
                trackBehavior: ruleForm.trackBehavior ? 1 : 0, //文章追踪-行为通知，0为未选中，1为选中，默认未选中
                trackDynamic: 1 //文章追踪-动态通知，0为未选中，1为选中，默认未选中
            };
            if (ruleForm.changeTitle == 1) {
                obj.id = ruleForm.id;
            }
            obj.arBody = obj.arBody
                .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/gi, '<img$1')
                .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/gi, '<img$1')
                .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/gi, '<img$1')
                .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/gi, '<img$1')
                .replace(/<img([\s\w"-=\/\.:;]+)/gi, '<img style="width: 100%;" $1');
            newAndEditArticle(obj, ruleForm.changeTitle == 0 ? 'post' : 'put').then((res) => {
                if (res.data.code === 0) {
                    if (marketingState !== 2) {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                    }
                    if (marketingState === 1) {
                        this.$emit('newAndEditArticleSaveFn');
                    } else {
                        if (obj.id) {
                            this.articleReleaseFn(obj.id);
                        } else {
                            this.articleReleaseFn(res.data.data.id);
                        }
                    }
                }
            });
        },
        //发布文章
        articleReleaseFn(id) {
            articleRelease(id).then((res) => {
                if (res.data.code === 0) {
                    this.$message({
                        message: '保存并发布成功',
                        type: 'success'
                    });
                    this.$emit('newAndEditArticleSaveFn');
                }
            });
        },
        handleClose() {}
    }
};
</script>

<style lang="scss" scoped>
/deep/.ql-editor {
    min-height: 200px;
}

.avatar-uploader {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40%;
    height: 200px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    .madp-article-cover {
        object-fit: contain;
        width: 240px;
        height: 190px;
    }
}
/deep/.el-upload {
    width: 100%;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.madp-buttons {
    margin-top: 30px;
    display: flex;
    justify-content: space-around;
    .el-button--medium {
        width: 120px;
    }
}
.madp-checked-dynamic {
    display: flex;
    white-space: pre-wrap;
    margin-top: 20px;
}
.madp-from {
    margin-top: 10px;
}
.madp-article-track-behavior {
    margin-top: 20px;
}
/*字体样式*/
/*//默认的样式*/
.ql-container {
    font-size: 14px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='10px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='10px']::before {
    content: '10px';
    font-size: 10px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='12px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='12px']::before {
    content: '12px';
    font-size: 12px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='14px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='14px']::before {
    content: '14px';
    font-size: 14px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='16px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='16px']::before {
    content: '16px';
    font-size: 16px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='18px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='18px']::before {
    content: '18px';
    font-size: 18px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='20px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='20px']::before {
    content: '20px';
    font-size: 20px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='24px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='24px']::before {
    content: '24px';
    font-size: 24px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='28px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='28px']::before {
    content: '28px';
    font-size: 28px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='32px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='32px']::before {
    content: '32px';
    font-size: 32px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='36px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='36px']::before {
    content: '36px';
    font-size: 36px;
}
</style>
